#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
//#include "user/ulib.c"
#include "kernel/fs.h"

char Filename[128];

char*
fmtname(char *path)
{
  static char buf[DIRSIZ+1];
  char *p;

  // Find first character after last slash.
  for(p=path+strlen(path); p >= path && *p != '/'; p--)
    ;
  p++;

  // Return blank-padded name.
  if(strlen(p) >= DIRSIZ)
    return p;
  memmove(buf, p, strlen(p));
  buf[strlen(p)]=0;
  //memset(buf+strlen(p), ' ', DIRSIZ-strlen(p));
  return buf;
}

void
find(char *path)
{
  char buf[512], *p;
  int fd;
  struct dirent de;
  struct stat st;

  if((fd = open(path, 0)) < 0){
    fprintf(2, "ls: cannot open %s\n", path);
    return;
  }

  if(fstat(fd, &st) < 0){
    fprintf(2, "ls: cannot stat %s\n", path);
    close(fd);
    return;
  }
  //printf("<<%s>>\n",path);
  switch(st.type){
  case T_FILE:
    //printf("%s %d %d %l\n", fmtname(path), st.type, st.ino, st.size);
    //printf("file-> <%s>\n",path);
    if(strcmp(fmtname(path),Filename)==0){
      printf("%s\n",path);
      //printf("************\n ***********\n");
    }
    break;

  case T_DIR:
    if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
      printf("ls: path too long\n");
      break;
    }
    strcpy(buf, path);
    p = buf+strlen(buf);
    *p++ = '/';
    while(read(fd, &de, sizeof(de)) == sizeof(de)){
      if(de.inum == 0)
        continue;
      memmove(p, de.name, DIRSIZ);
      //printf("<<<%s>>>\n",buf);
      if(stat(buf, &st) < 0){
        printf("ls: cannot stat %s\n", buf);
        continue;
      }
      //printf("%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size);
      if(strcmp(fmtname(buf),".")==0||strcmp(fmtname(buf),"..")==0)continue;
      //printf("<<%s>>\n",buf);
      find(buf);
    }
    break;
  }
  close(fd);
}



int
main(int argc, char *argv[])
{

  if(argc != 3){
    fprintf(2,"usage: find <main_path> <file_name>\n");
    exit(1);
  }
  
  //printf("<<<<here>>>>>");

  memmove(Filename,argv[2],strlen(argv[2]));
  memset(Filename+strlen(argv[2]),0,128-strlen(argv[2]));

  //printf("<<<<here>>>>>");

  char p[128];
  memmove(p,argv[1],strlen(argv[1]));
  memset(p+strlen(argv[1]),0,128-strlen(argv[1]));
  if(strcmp(p,".")!=0){
    int i=strlen(p);
    for(;i>=0;i--){
      p[i+2]=p[i];
    }
    p[0]='.';
    p[1]='/';
  }
  //p[strlen(p)]='/';
  //printf("<<%s>>   <<%s>>\n",Filename,p);
  find(p);
  exit(0);
}




